<?php

namespace App\Listeners\Kms;

use App\Events\Kms\PunchShareEvent;
use App\Library\FeiShu\SendFs;
use App\Listeners\BaseListener;
use App\Models\Kms\Album\AlbumResourceModel;
use App\Service\Kms\Album\AlbumMainService;
use App\Service\Kms\Common\DateService;
use App\Service\Kms\System\SystemService;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;

class PunchShareListener extends BaseListener
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * @param PunchShareEvent $punchShareEvent
     * @throws GuzzleException
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function handle(PunchShareEvent $punchShareEvent)
    {
        try {
            $albumResourceModel = AlbumResourceModel::query()->where("id", $punchShareEvent->resourceId)->first();
            $fsImgKey           = AlbumResourceModel::getFsImgKey($albumResourceModel, "punchShare");

            $formatTime          = DateService::translateDate(time());
            $msgTemplateContents = view()->file(
                app_path("Remote/Feishu/FsTemplate/Kms") . "/PunchShareTemplate.blade.php",
                [
                    "remark"        => str_replace(["\n", "\r"], '\n', $punchShareEvent->remark),
                    "username"      => vsprintf("%s (%s)", [
                        attributeGet($punchShareEvent, "shareUser.name", ""),
                        attributeGet($punchShareEvent, "shareUser.nickname", "")
                    ]),
                    "date"          => date("Y.m.d", time()),
                    "week"          => $formatTime["weekDayCn"],
                    "time"          => date("H:i", time()),
                    "address"       => $albumResourceModel->poiName,
                    "weather"       => $albumResourceModel->weather,
                    "imgKey"        => $fsImgKey,
                    "addressPrefix" => $albumResourceModel->addressPrefix,
                    "type"          => collect($punchShareEvent->punchType)->map(function (int $type) {
                        return SystemService::PUNCH_TYPE_TEXT[$type];
                    })->implode(" | ")
                ]
            )->render();

            collect(
                AlbumMainService::groupList(true)["groupList"]
            )->map(function ($v, $key) {
                return array_merge($v, ["id" => $key]);
            })->whereIn("id", $punchShareEvent->groupIds)->each(function ($group) use ($msgTemplateContents) {
                collect($group["robots"] ?? [])->each(function ($fsRobot) use ($msgTemplateContents) {
                    SendFs::newRobot()
                          ->coverConfig($fsRobot["webhook"], $fsRobot["secret"])
                          ->setCardMessageBody(json_decode($msgTemplateContents, true))
                          ->send();
                });
            });
        } catch (\Exception $exception) {
            logException("打卡分享失败", $exception, get_object_vars($punchShareEvent), true, true);
        }
    }
}
